<template>
    <div>
        <el-row :gutter="20" ref="helloWorld">
            <el-col :span="12">
                <el-card shadow="hover">
                    <template #header>
                        <div class="clearfix">
                            <span>基础信息</span>
                        </div>
                    </template>
                    <div class="info">
                        <div class="info-image" @click="showDialog">
                            <img :src="avatarImg" />
                            <span class="info-edit">
                                <i class="el-icon-lx-camerafill"></i>
                            </span>
                        </div>
                        <div class="info-name">{{form.username}}</div>
                        <div class="info-desc">{{form.desc}}</div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="hover">
                    <template #header>
                        <div class="clearfix">
                            <span>账户编辑</span>
                        </div>
                    </template>
                    <el-form label-width="90px">
                        <el-form-item label="用户名："> {{form.username}} </el-form-item>
	                    <el-form-item label="昵 称 ：">
		                    <el-input type="text" v-model.trim="form.realname" maxlength="30" show-word-limit></el-input>
	                    </el-form-item>
                        <el-form-item label="旧密码：">
                            <el-input type="password" v-model.trim="form.old" maxlength="30"></el-input>
                        </el-form-item>
                        <el-form-item label="新密码：">
                            <el-input type="password" v-model.trim="form.new" maxlength="30"></el-input>
                        </el-form-item>
                        <el-form-item label="个人简介：">
                            <el-input v-model="form.desc" maxlength="100" show-word-limit></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit" size="small">保存</el-button>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog title="裁剪图片" v-model="dialogVisible" width="600px">
            <vue-cropper ref="cropper" :src="imgSrc" :ready="cropImage" :zoom="cropImage" :cropmove="cropImage"
                style="width: 100%; height: 400px"></vue-cropper>
            <template #footer>
                <span class="dialog-footer">
                    <el-button class="crop-demo-btn" type="primary">选择图片
                        <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
                    </el-button>
                    <el-button type="primary" @click="saveAvatar">上传并保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { reactive, ref,getCurrentInstance } from "vue";
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";
import {imageBase64Resize, base64toFile} from "../utils/imgHandle";
import request from "../utils/request";
import AxiosOrigin from "axios"
import {ElMessage} from "element-plus";
import config from "../utils/config";
import {useStore} from "vuex";
import {getUserInfo} from "../api/api";
import Methods from "../utils/Methods";

export default {
    name: "user",
    components: {
        VueCropper,
    },
    setup() {
	    const store = useStore();
        const form = reactive({
	        username: "",
	        realname:"",
            old: "",
            new: "",
            desc: "",
        });
        const avatarImg = ref('');
        const imgSrc = ref("");
        const cropImg = ref("");
        const dialogVisible = ref(false);
        const cropper = ref(null);

        const getData = () => {
        	getUserInfo({token:Methods.getLocalStorage('admin_token')}).then(res => {
		        form.username = res.username
		        form.realname = res.realname
		        form.desc = res.desc
		        Methods.setLocalStorage('admin_realname',res.realname)
		        Methods.setLocalStorage('admin_avatar',res.avatar)
		        avatarImg.value = (res.avatar && res.avatar.slice(0,4) === 'http') ? res.avatar : config.imgPath + res.avatar
            console.log("avatarImg.value = ",avatarImg.value)
		        store.commit("setUserinfo");
	        }).catch(err => {
		        console.log(err)
	        })
        }
        getData()
        const showDialog = () => {
	        console.log('弹出showDialog')
            dialogVisible.value = true;
            imgSrc.value = avatarImg.value;
        };
        const setImage = (e) => {
            const file = e.target.files[0];
            if (!file.type.includes("image/")) {
                return;
            }
            const reader = new FileReader();
            reader.onload = (event) => {
                dialogVisible.value = true;
                imgSrc.value = event.target.result;
                cropper.value && cropper.value.replace(event.target.result);
            };
            reader.readAsDataURL(file);
        };
        const cropImage = () => {
	        console.log('-------------cropImage')
            cropImg.value = cropper.value.getCroppedCanvas().toDataURL();
        };
	    const saveAvatar = () => {
	        let base64 = cropImg.value;
	        new Promise(resolve => {
		        imageBase64Resize(base64, 500, (base64) => {
			        resolve(base64)
		        })
	        }).then(res => {
		        let file = base64toFile(res,'tmp')
		        return {
              file: file
            }
	        }).then(res => {
		        let param = new FormData(); // 创建form对象
		        param.append("file", res.file);
            // console.log("file: ",res.file)
		        return AxiosOrigin.post('/manage/upload/uploadImage',param,{headers:{"Content-Type":"multipart/form-data",Authorization: Methods.getLocalStorage('token')}}).then(res => {
			        if(res.status === 200) {
                res = res.data
                console.log("upload res", res.code)
                if(res.code === 1) {
                  ElMessage.success('上传成功')
                  dialogVisible.value = false
                  return res.data
                }else {
                  ElMessage.error(res.message)
                }
				        return ""
			        }else {
			        	ElMessage.error('上传失败')
				        return Promise.reject(res)
			        }
		        })
	        }).then(res => {
		        console.log('开始修改头像' + res)
		        return request.post('/manage/Index/avatarMod',{pic : res.url})
	        }).then(res => {
            console.log("res", res)
            let newAvatar = res.avatar
            Methods.setLocalStorage('avatar',newAvatar)
            avatarImg.value = config.imgPath + newAvatar
            store.commit("setUserinfo");
          }).catch(err => {
		        console.log(err,'----user catch')
	        })
        }
        let isClick = false
	    const onSubmit = () => {
	    	let data = {
	    		token: Methods.getLocalStorage('admin_token'),
			    realname: form.realname,
			    desc: form.desc
		    }
	    	if(form.new && form.old) {
	    		data.password = form.old
	    		data.newpassword = form.new
		    }else {
	    		if(form.new || form.old) {
				    ElMessage.error('请输入密码')
				    return false
			    }
		    }
	    	if(!isClick) {
	    		isClick = true
          request.post('/manage/Index/userMod',data).then(res => {
				    ElMessage.success('修改成功')
				    Methods.setLocalStorage('realname',data.realname)
				    store.commit("setUserinfo")
				    setTimeout(() => {
					    isClick = false
				    },1500)
			    }).catch(err => {
				    isClick = false
				    console.log(err)
			    })
		    }

	    }
        return {
            form,
            onSubmit,
            cropper,
            avatarImg,
            imgSrc,
            cropImg,
            showDialog,
            dialogVisible,
            setImage,
            cropImage,
            saveAvatar,
        };
    },
};
</script>

<style scoped>
.info {
    text-align: center;
    padding: 35px 0;
}
.info-image {
    position: relative;
    margin: auto;
    width: 100px;
    height: 100px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 50px;
    overflow: hidden;
}
.info-image img {
    width: 100%;
    height: 100%;
}
.info-edit {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    transition: opacity 0.3s ease;
}
.info-edit i {
    color: #eee;
    font-size: 25px;
}
.info-image:hover .info-edit {
    opacity: 1;
}
.info-name {
    margin: 15px 0 10px;
    font-size: 24px;
    font-weight: 500;
    color: #262626;
}
.crop-demo-btn {
    position: relative;
}
.crop-input {
    position: absolute;
    width: 100px;
    height: 40px;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}
</style>
